//
//  UINavigationBar+Draw.m
//  collection
//
//  Created by 张靖.
//

#import "UINavigationBar+Draw.h"
#import "CImageHelper.h"

@implementation UINavigationBar (Draw)

static UIColor* _backgroundColor = nil;
+ (UIColor*) customBackgroundColor
{
	return _backgroundColor == nil ? [UIColor blackColor] : _backgroundColor;
}

static UIImage* _backgroundImage = nil;
+ (UIImage*) customBackgroundImage
{
	return _backgroundImage;
}

+ (void) setCustomBackgroundColor:(UIColor*)color
{
	[color retain];
	[_backgroundColor release];
	_backgroundColor = color;
	if (_backgroundColor == nil)
	{
		_backgroundColor = [[UIColor blackColor] retain];
	}
	
	if ([[UIDevice currentDevice].systemVersion doubleValue] >= 5.0)
	{
		[[UINavigationBar appearance] setBackgroundImage:[CImageHelper getImage:CGSizeMake(5, 5) withColor:[UINavigationBar customBackgroundColor]] 
										   forBarMetrics:UIBarMetricsDefault];
	}
}

+ (void) setCustomBackgroundImage:(UIImage*)backgroundImage
{
	[backgroundImage retain];
	[_backgroundImage release];
	_backgroundImage = backgroundImage;
	
	if (backgroundImage != nil && [[UIDevice currentDevice].systemVersion doubleValue] >= 5.0)
	{
		[[UINavigationBar appearance] setBackgroundImage:backgroundImage 
										   forBarMetrics:UIBarMetricsDefault];
	}
}

- (void) drawRect:(CGRect)rect
{
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	UIImage* backgroundImage = [UINavigationBar customBackgroundImage];
	if (backgroundImage != nil)
	{
		[backgroundImage drawInRect:self.bounds];
	}
	else 
	{
		UIColor* backgroundColor = [UINavigationBar customBackgroundColor];
		[backgroundColor set];
		CGContextFillRect(ctx, self.bounds);
	}
}

+ (void) setNeedsLayoutDeep:(UIView*)view
{
	if ([view isKindOfClass:[UINavigationBar class]] && ![[UIApplication sharedApplication] isStatusBarHidden])
	{
		CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
		CGRect frame = view.frame;
		frame.origin.x = 0;
		frame.origin.y = screenFrame.origin.y;
		frame.size.width = screenFrame.size.width;
		frame.size.height = kNavigationBarHeight;
		view.frame = frame;
	}
	[view setNeedsLayout];
	
	NSArray* subViews = [view subviews];
	if (subViews != nil)
	{
		for (UIView* v in subViews)
		{
			[self setNeedsLayoutDeep:v];
		}
	}
}

@end
